﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Entity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using ThoughtWorks.QRCode;
using ThoughtWorks.QRCode.Codec;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers
{

    /// <summary>
    /// 
    /// </summary>
    public class HappyLandDownLoadController : Controller
    {
        private readonly IIcApiService _icApiService;
        private readonly string _apitoken;
        private readonly string appkey;
        private readonly string signKey;
        private readonly string apptoken;
        private readonly IStockService _stockService;
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("BizInfo");
        private readonly string apiname = "";
        private readonly IStoreService _storeService;
        private readonly IErrorLogService _errorLogService;
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Controllers.DownLoadController"/> class.
        /// </summary>
        /// <param name="snapshot">Snapshot.</param>
        /// <param name="storeService">Store service.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="mini">Mini.</param>
        /// <param name="settings">Settings.</param>
        /// <param name="stockService">Stock service.</param>
        /// <param name="errorLogService"></param>
        public HappyLandDownLoadController(IOptionsSnapshot<Common.CasamielSettings> snapshot, IStoreService storeService,
            IIcApiService iicApiService,   IOptionsSnapshot<List<Common.MiniAppSettings>> mini,
  IOptionsSnapshot<IcServiceSettings> settings,
                                      IStockService stockService,IErrorLogService errorLogService)

        {
            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }

            _storeService = storeService;
            _icApiService = iicApiService;
            _apitoken = snapshot.Value.ApiToken;
            appkey = settings.Value.appKey;
            signKey = settings.Value.signKey;
            apptoken = settings.Value.token;
            if (snapshot.Value.ApiName == "casamielnetwork") {
                apiname = "casa";

            }
            _stockService = stockService;
            _errorLogService = errorLogService;
        }
        /// <summary>
        /// Index this instance.
        /// </summary>
        /// <returns>The index.</returns>
        public IActionResult Index()
        {
            var head = Request.Headers["User-Agent"].ToString();
            logger.Trace($"DownLoad,User-Agent{head},IP:{Request.GetUserIp()}");
            if (head.Contains("iPhone")) {
                if (apiname == "casa") {
                    return Redirect("https://apps.apple.com/cn/app/id1479654554");
                }
            } else if (head.Contains("Linux") || head.Contains("Android", StringComparison.InvariantCulture)) {
                if (apiname == "casa") {
                    var appurl = _errorLogService.GetHappyLandAppUrlAsnyc().GetAwaiter().GetResult();
                    return Redirect(appurl);
                }
            } else {
                return Ok("");
            }
            return Ok("");
        }

        /// <summary>
        /// Donco the specified MID.
        /// </summary>
        /// <returns>The donco.</returns>
        /// <param name="MID">Middle.</param>
        public    IActionResult Donco(string MID)
        {
            string path = $"{AppContext.BaseDirectory}//logs//casashop//{MID}.png";
            var str = MID.ToString();
            //初始化二维码生成工具
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeVersion = 5;
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
          
            qrCodeEncoder.QRCodeScale = 4;

            //将字符串生成二维码图片
            Bitmap image = qrCodeEncoder.Encode(str, Encoding.Default);
            image.Save(path);
            //保存为PNG到内存流  
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);
            
           
            return Ok("");
        }

        
        /// <summary>
        /// Adds the mbr extend info.
        /// </summary>
        /// <returns>The mbr extend info.</returns>
        /// <param name="mid">Middle.</param>
        /// <param name="userAgent">User agent.</param>
        private async Task AddMbrExtendInfo(int mid, string userAgent)
        {
            try {
                var m = new MbrExtendInfoEntity { MemberId = mid, UserAgent = userAgent, CreateTime = DateTime.Now };
                await _storeService.AddMbrExtendInfoAsync<ICasaMielSession>(m).ConfigureAwait(false);
            } catch (System.Data.SqlClient.SqlException ex) {
                logger.Error(ex.Message);
                throw;
            }

        }



    }
    /// <summary>
    /// Down load controller.
    /// </summary>
    public class DownLoadController : Controller
    {
        private readonly IIcApiService _icApiService;
        private readonly string _apitoken;
        private readonly string appkey;
        private readonly string signKey;
        private readonly string apptoken;
        private readonly IStockService _stockService;
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("BizInfo");
        private readonly string apiname = "";
        private readonly IStoreService _storeService;
        private readonly IErrorLogService _errorLogService;

       /// <summary>
       /// 
       /// </summary>
       /// <param name="snapshot"></param>
       /// <param name="storeService"></param>
       /// <param name="iicApiService"></param>
       /// <param name="session"></param>
       /// <param name="paymentService"></param>
       /// <param name="mini"></param>
       /// <param name="settings"></param>
       /// <param name="stockService"></param>
       /// <param name="errorLogService"></param>
        public DownLoadController(IOptionsSnapshot<Common.CasamielSettings> snapshot, IStoreService storeService,
            IIcApiService iicApiService, Casamiel.Application.ICasaMielSession session, IPaymentService paymentService, IOptionsSnapshot<List<Common.MiniAppSettings>> mini,
  IOptionsSnapshot<IcServiceSettings> settings,
                                      IStockService stockService, IErrorLogService errorLogService)

        {
            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }
            _errorLogService = errorLogService;
            _storeService = storeService;
            _icApiService = iicApiService;
            _apitoken = snapshot.Value.ApiToken;
            appkey = settings.Value.appKey;
            signKey = settings.Value.signKey;
            apptoken = settings.Value.token;
            if (snapshot.Value.ApiName == "casamielnetwork") {
                apiname = "casa";

            }
            _stockService = stockService;
        }
        /// <summary>
        /// Index this instance.
        /// </summary>
        /// <returns>The index.</returns>
        public IActionResult Index()
        {
            var head = Request.Headers["User-Agent"].ToString();
            logger.Trace($"DownLoad,User-Agent{head},IP:{Request.GetUserIp()}");
            if (head.Contains("iPhone")) {
                if (apiname == "casa") {
                    return Redirect("https://itunes.apple.com/cn/app/%E5%8F%AF%E8%8E%8E%E8%9C%9C%E5%85%92/id1332241823");
                }
            } else if (head.Contains("Linux") || head.Contains("Android", StringComparison.InvariantCulture)) {
                if (apiname == "casa") {
                    return Redirect("http://a.app.qq.com/o/simple.jsp?pkgname=com.meriland.casamiel");
                }
            } else {
                return Ok("");
            }
            return Ok("");
        }


        /// <summary>
        /// 后台
        /// </summary>
        /// <returns></returns>
        public IActionResult Back()
        {
            var appurl = _errorLogService.GetAppDownloadUrlAsnyc(1).GetAwaiter().GetResult();
            return Redirect(appurl);
        }
        /// <summary>
        /// Donco the specified MID.
        /// </summary>
        /// <returns>The donco.</returns>
        /// <param name="MID">Middle.</param>
        public async Task<IActionResult> Donco(string MID)
        {
            var mid = MID.ToInt32(0);
            var userAgent = Request.Headers["User-Agent"].ToString();
            logger.Trace($"DownLoad,User-Agent{userAgent},IP:{Request.GetUserIp()}");
            if (userAgent.Contains("iPhone")) {
                await AddMbrExtendInfo(mid, userAgent).ConfigureAwait(false);
                return Redirect("https://itunes.apple.com/cn/app/%E4%B8%9C%E5%93%A5%E7%83%98%E7%84%99-%E4%B8%A5%E9%80%89%E9%9D%A2%E5%8C%85/id1436916926");

            } else if (userAgent.Contains("Linux", StringComparison.OrdinalIgnoreCase) || userAgent.Contains("Android", StringComparison.OrdinalIgnoreCase)) {
                await AddMbrExtendInfo(mid, userAgent).ConfigureAwait(false);
                return Redirect("https://a.app.qq.com/o/simple.jsp?pkgname=com.meriland.donco");
            } else {
                return Ok(MID);
            }

        }

        /// <summary>
        /// Adds the mbr extend info.
        /// </summary>
        /// <returns>The mbr extend info.</returns>
        /// <param name="mid">Middle.</param>
        /// <param name="userAgent">User agent.</param>
        private async Task AddMbrExtendInfo(int mid, string userAgent)
        {
            try {
                var m = new MbrExtendInfoEntity { MemberId = mid, UserAgent = userAgent, CreateTime = DateTime.Now };
                await _storeService.AddMbrExtendInfoAsync<ICasaMielSession>(m).ConfigureAwait(false);
            } catch (System.Data.SqlClient.SqlException ex) {
                logger.Error(ex.Message);
                throw;
            }

        }



    }
}
